package com.linuxgt.mobile.controller;

import com.linuxgt.mobile.WeChatTextMessage;
import com.linuxgt.mobile.common.WLAppconfig;
import com.linuxgt.mobile.exception.errorMessageFormatException;
import com.linuxgt.mobile.replydomain.WeChatReplyMusicMessage;
import com.linuxgt.mobile.replydomain.WeChatReplyPicTextItemMessage;
import com.linuxgt.mobile.replydomain.WeChatReplyPicTextMessage;
import com.linuxgt.mobile.replydomain.WeChatReplyTextMessage;
import com.linuxgt.mobile.security.Validate;
import com.linuxgt.mobile.senddomain.WeChatEventMessage;
import com.linuxgt.mobile.senddomain.WeChatLbsMessage;
import com.linuxgt.mobile.senddomain.WeChatLinkMessage;
import com.linuxgt.mobile.senddomain.WeChatPicMessage;
import com.linuxgt.mobile.utils.xmlTools;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.apache.cxf.helpers.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Servlet implementation class HelloWeChat 
 */
@Controller("com.linuxgt.mobile.controller.HelloWeChat")
@RequestMapping("/wc/*")
public class HelloWeChat{
    private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWeChat() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @RequestMapping(value = "/liutengweixin",method = RequestMethod.GET)
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get start...");//TODO 测试代码发布时移除
        response.setContentType("text/html;charset=UTF-8");
        //参考代码，不做校验原样返回
//        String echo = request.getParameter("echostr");
//        pw.println(echo);
        String echoStr=request.getParameter("echostr");
        try {
            if(Validate.checkSignature(request)){
                PrintWriter wt = response.getWriter();
                wt.write(echoStr);
                wt.close();
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        System.out.println("get end...");//TODO 测试代码发布时移除
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @RequestMapping(value = "/liutengweixin",method = RequestMethod.POST)
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, errorMessageFormatException {

        System.out.println("post start...");//TODO 测试代码发布时移除
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        String wxMsgXml = IOUtils.toString(request.getInputStream(), "utf-8");

        //定义微信服务器post过来的数据目前有五种
          Object msg=null;//接收的消息对象
//        WeChatTextMessage textMsg = null;
//        WeChatPicMessage picMsg=null;
//        WeChatLbsMessage lbsMsg=null;
//        WeChatLinkMessage linkMsg=null;
//        WeChatEventMessage eventMsg=null;

        //取得post过来的数据生成对应的消息类型对象
        if(wxMsgXml.contains("<MsgType><![CDATA[text]]></MsgType>")){
            try {
                msg = getWeChatTextMessage(wxMsgXml);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(wxMsgXml.contains("<MsgType><![CDATA[image]]></MsgType>")){
            try {
                msg = getWeChatPicMessage(wxMsgXml);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(wxMsgXml.contains("<MsgType><![CDATA[location]]></MsgType>")){
            try {
                msg = getWeChatLbsMessage(wxMsgXml);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if(wxMsgXml.contains("<MsgType><![CDATA[link]]></MsgType>")){
            try {
                msg = getWeChatLinkMessage(wxMsgXml);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if(wxMsgXml.contains("<MsgType><![CDATA[event]]></MsgType>")){
            try {
                msg = getWeChatEventMessage(wxMsgXml);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else try {
            throw new errorMessageFormatException();
        } catch (errorMessageFormatException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        //定义回复内容存储变量
        StringBuffer replyMsg = new StringBuffer();

//        if(textMsg != null){
//            //增加你所需要的处理逻辑，这里只是简单重复消息
//            replyMsg.append("您给我的消息是：");
//            replyMsg.append(textMsg.getContent());
//        }
//        else{
//            replyMsg.append(":)不是文本的消息，我暂时看不懂");
//        }
//        String returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName());
        //TODO 回复信息到微信服务器，由处理器根据接收信息内容来决定回复的内容
        String returnXml = linuxgtWXProcessor(msg);
        System.out.println(msg.toString());//TODO 测试代码发布时移除
        pw.println(returnXml);
        pw.flush();
        pw.close();
        System.out.println("post end...");//TODO 测试代码发布时移除
    }

    /**
     * 玄罡微信处理器
     * @param msg is come from user
     * @return 格式化消息到微信服务器
     * @throws errorMessageFormatException
     */
     private String linuxgtWXProcessor(Object msg) throws errorMessageFormatException {
        if(msg instanceof WeChatTextMessage){
            WeChatTextMessage textMessage;
            textMessage=(WeChatTextMessage)msg;
            //TODO 在根据用户发送文本内容返回任意想返回的一切信息，可调用第三方接口，本地数据库等资源

            if(textMessage.getContent().equals("1")){
                return getReplyTextMessage(textMessage.getContent(),textMessage.getFromUserName());
            }if(textMessage.getContent().equals("2")){
                return getReplyPicTextMessage(textMessage.getContent(),textMessage.getFromUserName());
            }


        }else if(msg instanceof WeChatPicMessage){
            msg=(WeChatPicMessage)msg;
//        }else if(msg instanceof WeChatLbsMessage){
//            WeChatLbsMessage weChatLbsMessage;
//            weChatLbsMessage=(WeChatLbsMessage)msg;
//            return getReplyTextMessage(weChatLbsMessage);
        }else if(msg instanceof WeChatLinkMessage){
            msg=(WeChatLinkMessage)msg;
//        }else if(msg instanceof WeChatEventMessage){
//            WeChatEventMessage weChatEventMessage;
//            weChatEventMessage=(WeChatEventMessage)msg;
//            if(weChatEventMessage.getEvent().equals("subscribe"))
//                return getReplyTextMessage(weChatEventMessage);
//            else return "";
        }else throw new errorMessageFormatException();
        return "未能理解您的意思，请重新输入！";  //To change body of created methods use File | Settings | File Templates.
    }



    /**
     * 返回事件消息对象
     * @param xml
     * @return
     */
    private WeChatEventMessage getWeChatEventMessage(String xml) {
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatEventMessage.class);
        xstream.aliasField("ToUserName", WeChatEventMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatEventMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatEventMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatEventMessage.class, "msgType");
        xstream.aliasField("Event", WeChatEventMessage.class, "event");
        xstream.aliasField("EventKey", WeChatEventMessage.class, "eventKey");
        WeChatEventMessage weChatEventMessage = (WeChatEventMessage)xstream.fromXML(xml);
        return weChatEventMessage;
    }

    /**
     * 返回链接消息对象
     * @param xml
     * @return
     */
    private WeChatLinkMessage getWeChatLinkMessage(String xml) {
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatLinkMessage.class);
        xstream.aliasField("ToUserName", WeChatLinkMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatLinkMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatLinkMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatLinkMessage.class, "msgType");
        xstream.aliasField("Title", WeChatLinkMessage.class, "title");
        xstream.aliasField("Description", WeChatLinkMessage.class, "description");
        xstream.aliasField("Url", WeChatLinkMessage.class, "url");
        xstream.aliasField("MsgId", WeChatLinkMessage.class, "msgId");
        WeChatLinkMessage weChatLinkMessage = (WeChatLinkMessage)xstream.fromXML(xml);
        return weChatLinkMessage;
    }

    /**
     * 返回物理位置消息对象
     * @param xml
     * @return
     */
    private WeChatLbsMessage getWeChatLbsMessage(String xml) {
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatLbsMessage.class);
        xstream.aliasField("ToUserName", WeChatLbsMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatLbsMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatLbsMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatLbsMessage.class, "msgType");
        xstream.aliasField("Location_X", WeChatLbsMessage.class, "location_X");
        xstream.aliasField("Location_Y", WeChatLbsMessage.class, "location_Y");
        xstream.aliasField("Scale", WeChatLbsMessage.class, "scale");
        xstream.aliasField("Label", WeChatLbsMessage.class, "label");
        xstream.aliasField("MsgId", WeChatLbsMessage.class, "msgId");
        WeChatLbsMessage weChatLbsMessage = (WeChatLbsMessage)xstream.fromXML(xml);
        return weChatLbsMessage;
    }

    /**
     * 返回图片消息对象
     * @param xml
     * @return
     */
    private WeChatPicMessage getWeChatPicMessage(String xml) {
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatPicMessage.class);
        xstream.aliasField("ToUserName", WeChatPicMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatPicMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatPicMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatPicMessage.class, "msgType");
        xstream.aliasField("PicUrl", WeChatPicMessage.class, "picUrl");
        xstream.aliasField("MsgId", WeChatPicMessage.class, "msgId");
        WeChatPicMessage weChatPicMessage = (WeChatPicMessage)xstream.fromXML(xml);
        return weChatPicMessage;
    }

    /**
     * 返回文本消息对象
     * @param xml
     * @return
     */
    private WeChatTextMessage getWeChatTextMessage(String xml){
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatTextMessage.class);
        xstream.aliasField("ToUserName", WeChatTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatTextMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatTextMessage.class, "msgType");
        xstream.aliasField("Content", WeChatTextMessage.class, "content");
        xstream.aliasField("MsgId", WeChatTextMessage.class, "msgId");
        WeChatTextMessage wechatTextMessage = (WeChatTextMessage)xstream.fromXML(xml);
        return wechatTextMessage;
    }

    /**
     * 回复文本消息
     * @param content
     * @param weChatUser
     * @return
     */
    private String getReplyTextMessage(String content, String weChatUser){
        WeChatReplyTextMessage we = new WeChatReplyTextMessage();
        we.setMsgType("text");
        we.setFuncFlag("0");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setContent(content);
        we.setToUserName(weChatUser);
        we.setFromUserName(WLAppconfig.WX_PUBLIC_ID);
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatReplyTextMessage.class);
        xstream.aliasField("ToUserName", WeChatReplyTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatReplyTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatReplyTextMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatReplyTextMessage.class, "msgType");
        xstream.aliasField("Content", WeChatReplyTextMessage.class, "content");
        xstream.aliasField("FuncFlag", WeChatReplyTextMessage.class, "funcFlag");
        String xml =xstream.toXML(we);
        return xmlTools.xml2string(xml);
    }

    /**
     * 回复音乐消息
     * @param content
     * @param weChatUser
     * @return
     */
    private String getReplyMusicMessage(String content, String weChatUser){
        WeChatReplyMusicMessage we = new WeChatReplyMusicMessage();
        we.setMsgType("music");
        we.setFuncFlag("0");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        //TODO  根据参数content回复不同的music
        we.setMusicUrl("musicurl");
        we.setHqMusicUrl("hqmusicurl");
        we.setToUserName(weChatUser);
        we.setFromUserName(WLAppconfig.WX_PUBLIC_ID);
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatReplyTextMessage.class);
        xstream.aliasField("ToUserName", WeChatReplyMusicMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatReplyMusicMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatReplyMusicMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatReplyMusicMessage.class, "msgType");
        xstream.aliasField("MusicUrl", WeChatReplyMusicMessage.class, "musicUrl");
        xstream.aliasField("HQMusicUrl", WeChatReplyMusicMessage.class, "hqMusicUrl");
        String xml =xstream.toXML(we);
        return xml;
    }

    /**
     * 回复文本消息
     * @param content
     * @param weChatUser
     * @return
     */
    private String getReplyPicTextMessage(String content, String weChatUser){
        WeChatReplyPicTextMessage we = new WeChatReplyPicTextMessage();
        we.setMsgType("news");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setToUserName(weChatUser);
        we.setFromUserName(WLAppconfig.WX_PUBLIC_ID);
        //根据传入的content参数决定要返回的图片(组)内容
        //TODO 此数值和图片地址来自于数据库，查询条件为传入的content
        we.setArticleCount(2);
        String[] weChatReplyPicTextItemMessages=new String[2];
        for(int i=0;i<weChatReplyPicTextItemMessages.length;i++){
            weChatReplyPicTextItemMessages[i]=getReplyPicTextItemMessage(content,i);
        }
        we.setArticles(weChatReplyPicTextItemMessages);
        //TODO 根据参数content回复不同的信息
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", WeChatReplyPicTextMessage.class);
        xstream.aliasField("ToUserName", WeChatReplyPicTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", WeChatReplyPicTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", WeChatReplyPicTextMessage.class, "createTime");
        xstream.aliasField("MsgType", WeChatReplyPicTextMessage.class, "msgType");
        xstream.aliasField("ArticleCount", WeChatReplyPicTextMessage.class, "articleCount");
        xstream.aliasField("Articles", WeChatReplyPicTextMessage.class, "articles");
        String xml =xstream.toXML(we);
        return xmlTools.xmlStreamRemoveStringTag(xmlTools.xml2string(xml));
    }

    /**
     * 获取单项图片信息
     * @param content
     * @param i
     * @return
     */
    private String getReplyPicTextItemMessage(String content, int i){
        WeChatReplyPicTextItemMessage we = new WeChatReplyPicTextItemMessage();
        we.setTitle("dq");
        we.setDescription("dqpic");
        we.setPicUrl("http://wx.linuxgt.com/springmvctest/wxpic/DQ.jpg");
        we.setUrl("http://www.linuxgt.com");
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("item", WeChatReplyPicTextItemMessage.class);
        xstream.aliasField("Title", WeChatReplyPicTextItemMessage.class, "title");
        xstream.aliasField("Description", WeChatReplyPicTextItemMessage.class, "description");
        xstream.aliasField("PicUrl", WeChatReplyPicTextItemMessage.class, "picUrl");
        xstream.aliasField("Url", WeChatReplyPicTextItemMessage.class, "url");
        String xml =xstream.toXML(we);
        return xmlTools.xml2string(xml);
    }
}